package JUC.阻塞队列;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author CKC
 * @DateTime 2021/4/1 19:46
 *
 * 题目: synchronized和Lock有什么区别?用新的Lock有什么好处?你举例说说
 * * 1.原始构成
 * * Synchronized是关键字属于 JVM 层
 * *    monitorenter(底层是通过monitor对象来完成，其实wait、notify等方法也依赖 monitor 对象只有在同步块或方法中才能调用wait、notify等方法
 * *    monitorexit  (javap.exe -c JUC.阻塞队列.SyncAndReentrantLockDemo
 * *                                        能看出monitorenter 进入一次，monitorexit退出两次，一次正常，一次异常退出)
 * * Lock是具体类（Java.util.concurrent.locks.lock）是API层面的锁
 *
 * *2.使用方法
 * *    synchronized不需要用户手动释放锁，当synchronized代码执行完后系统会自动让线程释放对锁的占用
 * *    ReentrantLock则需要用户手动去释放锁，若没有主动释放锁，就可能导致死锁现象。需要lock()和unlock()方法配合try/finally语句块来完成
 *
 * *3.等待是否可中断
 * *    synchronized 不可中断，除非抛出异常或者正常运行完成
 * *    ReentrantLock 可中断，1.设置超时方法 tryLock(long timeout,TimeUnit unit)
 * *                         2.lockInterruptibly()放代码块中，调用interrupt()方法可中断
 *
 * *4.加锁是否公平
 * *    synchronized 非公平锁
 * *    ReentrantLock两者都可以，默认是非公平锁，构造方法中可以传Boolean值，true为公平，false为非公平锁
 *
 * *5.锁绑定多个条件Condition
 * *    synchronized 没有
 * *    ReentrantLock 用来实现分组唤醒需要唤醒的线程，可以精确唤醒，而不是像synchronized要么随机唤醒一个线程要么唤醒全部线程
 */
@SuppressWarnings("all")
public class SyncAndReentrantLockDemo {
    public static void main(String[] args) {
        ShareDate shareDate = new ShareDate();
        new Thread(()->{
            for (int i = 1; i <= 10; i++) {
                shareDate.print5();
            }
        },"A").start();
    
        new Thread(()->{
            for (int i = 1; i <= 10; i++) {
                shareDate.print10();
            }
        },"Son").start();
    
        new Thread(()->{
            for (int i = 1; i <= 10; i++) {
                shareDate.print15();
            }
        },"C").start();
    }
}

/**
 * * 备注：多线程之间按顺序调用，实现A->Son->C
 *  * 三个线程启动，要求
 *  * <p>
 *  * AA打印5次，BB打印10次，CC打印15 次
 *  * 接着
 *  * AA打印5次，BB打印10次，CC打印15 次
 *  * 来10轮
 */
@SuppressWarnings("all")
class ShareDate {
    private int number = 1;//a:1    b:2     c:3
    private Lock lock = new ReentrantLock();
    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();
    private Condition c3 = lock.newCondition();
    
    
    public void print5() {
        lock.lock();
        try {
            while (number != 1) {
                c1.await();
            }
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            number = 2;
            c2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    
    public void print10() {
        lock.lock();
        try {
            while (number != 2) {
                c2.await();
            }
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            number = 3;
            c3.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    
    public void print15() {
        lock.lock();
        try {
            while (number != 3) {
                c3.await();
            }
            for (int i = 0; i < 15; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            number = 1;
            c1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}